import logging
from celery import shared_task
from celery.exceptions import MaxRetriesExceededError
from django.contrib.auth import get_user_model
from .models import PrivateMessage

logger = logging.getLogger(__name__)
User = get_user_model()

@shared_task(bind=True, max_retries=3, default_retry_delay=30)
def save_private_message(self, key, sender_id, receiver_id, content,timestamp):
    try:
        sender = User.objects.get(id=sender_id)
        receiver = User.objects.get(id=receiver_id)
        # 创建私聊消息
        PrivateMessage.objects.create(
            key=key,
            sender=sender,
            receiver=receiver,
            content=content,
            timestamp=timestamp
        )
        logger.info(f"Saved private message from {sender.username} to {receiver.username}")

    except User.DoesNotExist as exc:
        logger.error(f"User not found: {exc}")
        # 如果用户不存在，不再重试
    except Exception as exc:
        logger.error(f"Error saving private message: {exc}")
        try:
            # 其他异常重试
            self.retry(exc=exc)
        except MaxRetriesExceededError:
            logger.error("Max retries exceeded for saving private message")